const mongoose = require('mongoose')
const mongoosePaginate = require('mongoose-paginate')
const uiqueVlidator = require('mongoose-unique-validator')
const iparea = require('./iparea')


const schema = new mongoose.Schema({
   area: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'iparea',
  },
  name: {
    type: String,
    unique: true,
    required: [true, 'name必填']
  },
  xinhao: {
    type: String,
  },
  type: [
    {
      type: String,
      required: [true, 'type必填']
    }
  ],

  ip: [
    {
      type: String,
    }
  ],
  user: [
    {
      username:{type: String},
      password:{type: String}
    }
  ],
  remote: [
    {
      type:{type: String},
      tcp:{type: String},
      host:{type: String},
      username:{type: String}
    }
  ],
  url: {
    type: String,
  },
  //设备参数
  parameter: {
    type: String,
  },
  version: {
    type: String,
  },
  //采购日期
  cgrq: {
    type: String,
    get: v => moment(v).format('YYYY-MM'),
  },
  files:[
    {fileName:{ type:String, unique:true, required:[true,'filename必填']},
      fileSize:{type:String},
      file:{type:Buffer, required:[true,'文件内容必须']},
      date: {type: Date, default: Date.now}
    }
  ],
  beizhu: {
    type: String,
  },
}, {
  timestamps: {createdAt: 'createdAt', updatedAt: 'updateAt'}
});


// 自动增加版本号
/* Mongoose 仅在您使用时更新版本密钥save()。如果您使用update()，findOneAndUpdate()等等，Mongoose将不会 更新版本密钥。
作为解决方法，您可以使用以下中间件。参考 https://mongoosejs.com/docs/guide.html#versionKey */

schema.pre('findOneAndUpdate', function () {
  const update = this.getUpdate();
  if (update.__v != null) {
    delete update.__v;
  }
  const keys = ['$set', '$setOnInsert'];
  Object.keys(keys).forEach((key) => {
    if (update[key] != null && update[key].__v != null) {
      delete update[key].__v;
      if (Object.keys(update[key]).length === 0) {
        delete update[key];
      }
    }
  });
  update.$inc = update.$inc || {};
  update.$inc.__v = 1;
});

schema.plugin(mongoosePaginate);
schema.plugin(uiqueVlidator);

module.exports = mongoose.model('device', schema)
